<template>
  <view class="mobile-item-container">
	<uni-section :title="id ? '修改' : '新增'" type="line">
		<view class="example">
			<uni-forms ref="form" :model="formData" :rules="rules" labelWidth="80px">
				<uni-forms-item label="商品名称" required name="goodsId">
					<uni-data-select v-model="formData.goodsId" :localdata="goodsInfoList" >
					</uni-data-select>
				</uni-forms-item>
				<uni-forms-item label="销售日期" required name="salesTime">
					<uni-datetime-picker type="date" return-type="timestamp"  v-model="formData.salesTime" />
				</uni-forms-item>
				 
				<uni-forms-item label="销售类型" required name="userType">
					<uni-data-checkbox v-model="formData.userType" :localdata="userTypes" />
				</uni-forms-item>
				
				<uni-forms-item label="销售员" required name="userId">
					<uni-data-select v-model="formData.userId" :localdata="actions"  :disabled="disable">
					</uni-data-select>
				</uni-forms-item>
				
				<uni-forms-item label="销售总额" required name="salesTotal">
					<uni-easyinput v-model="formData.salesTotal" placeholder="请输入销售总额" @blur="calculateRetailPrice" />
				</uni-forms-item>
				
				<uni-forms-item label="销售数量" name="salesNum">
					<uni-easyinput v-model="formData.salesNum" placeholder="请输入销售数量" @blur="calculateRetailPrice"/>
				</uni-forms-item>
				
				<uni-forms-item label="零售价">
					<uni-easyinput v-model="formData.retailPrice"  disabled/>
				</uni-forms-item>
				<uni-forms-item label="备注">
					<uni-easyinput type="textarea" v-model="formData.remark" placeholder="请输入备注" />
				</uni-forms-item>
			</uni-forms>
			<view class="button-group">
				<u-row :gutter="12">
				  <u-col :span="4">
				    <u-button   v-if="id" type="error" text="删除" @click="del" v-hasPermi="['goods:goodsSalesInfo:remove']"></u-button>
				  </u-col>
				  <u-col :span="4">
				    <u-button icon="arrow-left" text="返回" plain @click="goBack()"></u-button>
				  </u-col>
				  <u-col :span="4">
					  <u-button v-if="!id" type="primary" text="新增" @click="submit" v-hasPermi="['goods:goodsSalesInfo:add']"></u-button>
					  <u-button  v-else type="primary" text="修改" @click="submit" v-hasPermi="['goods:goodsSalesInfo:edit']"></u-button>
				  </u-col>
				</u-row>
			</view>
		</view>
	</uni-section>
	
	<buttom-tabbar></buttom-tabbar>
  </view>
</template>

<script>
import * as GoodsSalesInfoApi from '@/api/goods/goodsSalesInfo'
import * as GoodsInfoApi from '@/api/goods/goodsInfo'
import * as DictInfoApi from '@/api/system/dict/data'
import * as UserInfoApi from '@/api/user'
import Navbar from '@/components/navbar/Navbar'

export default {
  components: {
    Navbar,
  },
  data () {
    return {
      id: undefined,
      formData:{
		 id: null,
		 goodsId: null,
		 salesTime: null,
		 salesTotal: null,
		 userId: null,
		 userName: null,
		 userType: "0",
		 createBy: null,
		 createTime: null,
		 updateBy: null,
		 updateTime: null,
		 remark: null
        },
	  nickName:"",
	  actions: [],
	  // 校验规则
	  rules: {
	  	goodsId: {
	  		rules: [{
	  			required: true,
	  			errorMessage: '商品名称不能为空'
	  		}]
	  	},
	  	salesTime: {
	  		rules: [{
	  			required: true,
	  			errorMessage: '销售日期不能为空'
	  		}]
	  	},
		userType: {
			rules: [{
				required: true,
				errorMessage: '销售类型不能为空'
			}]
		},
		userId: {
			rules: [{
				required: true,
				errorMessage: '销售员不能为空'
			}]
		},
	  	salesTotal: {
	  		rules: [{
	  			required: true,
	  			errorMessage: '销售总额不能为空'
	  		}, {
	  			format: 'number',
	  			errorMessage: '销售总额只能输入数字'
	  		}]
	  	},
	  	salesNum: {
	  		rules: [{
	  			format: 'number',
	  			errorMessage: '销售数量只能输入数字'
	  		}]
	  	}
	  },
	  goodsInfoList: [],
	  userTypes:[],
	  disable:true
    }
  },
  onLoad (params) {
	this.selectUserListByPostCode();
	this.getGoodsInfoList();
    this.id = params.id
	DictInfoApi.getDicts("user_type").then(res => {
		if(res.data)
		{
			if(res.data.length)
			{
				this.userTypes=[]
				for(let i=0;i<res.data.length;i++)
				{
					let temp = res.data[i];
					let obj = {};
					obj.value = temp.dictValue;
					obj.text = temp.dictLabel
					this.userTypes.push(obj);
				}
			}
		}
	});
	
	this.loadData()
	
	if(this.$auth.hasRole("system") || this.$auth.hasRole("admin"))
	{
		this.disable = false;
	}
  },
  methods: {
    loadData () {
      if (this.id) {
        const app = this
        GoodsSalesInfoApi.getGoodsSalesInfo(this.id).then(res => {
			if(res.data)
			{
				app.formData = res.data
				app.formData.userId = res.data.userId+""
				app.formData.userType = res.data.userType+""
			}
        })
      }else
	  {	
		  this.formData.userId = this.$store.getters.userId+""
		  this.formData.userType='0'
	  }
    },
	getGoodsInfoList()
	    {
			DictInfoApi.getDicts("unit").then(res => {
				if(res.data)
				{
					GoodsInfoApi.listAll().then(response => {
						this.goodsInfoList = [];
						if(response.rows)
						{
							if(response.rows.length)
							{
								for(let i=0;i<response.rows.length;i++)
								{
									let temp = response.rows[i];
									let obj = {};
									obj.value = temp.id;
									const dicts = res.data.find(i => i.dictValue === temp.unit)
									obj.text = temp.goodsName+"（"+dicts.dictLabel+"）"
									this.goodsInfoList.push(obj);
								}
							}
						}
					});
				}
			});
	    },
	selectUserListByPostCode()
	{
		UserInfoApi.selectUserDict().then((response) => {
				if(response.rows)
				{
					if(response.rows.length)
					{
						for(let i=0;i<response.rows.length;i++)
						{
							let temp = response.rows[i];
							let obj = {};
							obj.value = temp.userId;
							obj.text = temp.nickName
							this.actions.push(obj);
						}
					}
				}
		});
	},
    del() {
		let id = this.id
		uni.showModal({
			title: '提示',
			content: '确定要删除吗？',
			success: function (res) {
				if (res.confirm) {
					GoodsSalesInfoApi.delGoodsSalesInfo(id).then(res2 => {
					  uni.showToast({ title: '提交成功！' })
					  uni.navigateTo({ url: '/pages/goods/goodsSalesInfo/index'})
					})
				} else if (res.cancel) {
					console.log('用户点击取消');
				}
			}
		});
    },
    submit() {
		this.$refs.form.validate().then(res => {
		  if (this.id) {
		    GoodsSalesInfoApi.updateGoodsSalesInfo(this.formData).then(res => {
		      uni.showToast({ title: '提交成功！' })
					this.goBack()
		    })
		  } else {
		    GoodsSalesInfoApi.addGoodsSalesInfo(this.formData).then(res => {
		      uni.showToast({ title: '提交成功！' })
					this.goBack()
		    })
		  }
		});
    },
    goBack() {
		uni.navigateTo({ url: '/pages/goods/goodsSalesInfo/index'})
    },
	calculateRetailPrice()
	{
		if(parseInt(this.formData.salesNum)>0)
		{
		  this.formData.retailPrice = this.formData.salesTotal/this.formData.salesNum
		}else{
		  this.formData.retailPrice = 0
		}
	}
  }
}
</script>
<style lang="scss">
	.example {
		padding: 15px;
		background-color: #fff;
	}

	.segmented-control {
		margin-bottom: 15px;
	}

	.button-group {
		margin-top: 15px;
		display: flex;
		justify-content: space-around;
	}

	.form-item {
		display: flex;
		align-items: center;
		flex: 1;
	}

	.button {
		display: flex;
		align-items: center;
		height: 35px;
		line-height: 35px;
		margin-left: 10px;
	}
</style>
